package middleware

import (
	kutil "longblog/work/utils"
	"bytes"
	"errors"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	kcommon "longblog/framework/tools/common"
	"time"
)

func GetPreventToken(c *gin.Context) string {
	var buffer bytes.Buffer
	session := sessions.Default(c)
	t := fmt.Sprintf("%d", time.Now().UnixNano())
	buffer.WriteString(t)
	buffer.WriteString(c.Request.URL.Path)
	buffer.WriteString(kcommon.GetRandomString(20, 0))
	token := kutil.Sha256(buffer.String())
	session.Set("token", token)
	if err := session.Save(); err != nil {
		return errors.New("set token fail").Error()
	}
	return token
}

func VerifyPreventToken(c *gin.Context, token string) bool {
	session := sessions.Default(c)
	srcToken := session.Get("token")
	if srcToken == nil {
		return false
	}
	if token != srcToken {
		return false
	}
	session.Delete("token")
	if err := session.Save(); err != nil {
		return false
	}
	return true
}
